<template>
    <div>
        <van-nav-bar
                title="新增员工"
                left-text="返回"
                left-arrow
                border
                fixed
                @click-left="$router.go(-1)"
        />
        <div style="height:50px"></div>
        <div class="date-box">
            <div class="time-text">投保时间</div>
            <div class="line">
                <div class="border-line">
                    <van-field readonly clickable :value="timeValue"
                               @click="timePopupShow1 = true" right-icon="clock-o"/>
                </div>
            </div>
        </div>

        <van-popup v-model="timePopupShow1" position="bottom">
            <van-datetime-picker v-model="timeVal1" type="year-month" :min-date="minDate" :max-date="maxDate"
                                 :formatter="formatter" @cancel="timePopupShow1 = false" @confirm="timeConfirm1"/>
            <!-- <van-datetime-picker v-model="timeVal1" type="date" @cancel="timePopupShow1 = false" @confirm="timeConfirm1" /> -->
        </van-popup>

        <!-- <van-search placeholder="请输入投保人姓名" v-model="searchVal" @search="onSearch" /> -->
        <div class="kfStaffList">
            <el-table :data="tableData" border style="width: 100%" @selection-change="tableSelectChange">
                <el-table-column fixed type="selection" :selectable="checkSelectable"></el-table-column>
                <el-table-column prop="realname" label="姓名" width="70" fixed></el-table-column>
                <el-table-column prop="certificate_code" label="身份证号" width="170"></el-table-column>
                <el-table-column prop="sex_text" label="性别" width="50"></el-table-column>
                <el-table-column prop="age_str" label="年龄" width="50"></el-table-column>
                <el-table-column prop="certificate_type" label="工种" width="120"></el-table-column>
                <el-table-column prop="goods_name" label="产品" width="120"></el-table-column>
                <el-table-column prop="mobile" label="联系电话" width="120"></el-table-column>
                <el-table-column prop="unit_price" label="价格" width="120"></el-table-column>
                <el-table-column prop="is_verify_text" label="状态" width="120"></el-table-column>
                <el-table-column prop="update_time" label="最新更新时间" width="120"></el-table-column>
                <el-table-column label="操作" width="100">
                    <template slot-scope="scope">
                        <el-button @click="setUserInfo(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button @click="feedback(scope.row)" v-if="scope.row.is_verify == 2" type="text"
                                   size="small">反馈
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <van-pagination class="pagination" v-model="page" :page-count="pageCount" @change="pageChange"/>
            <div class="bottom-bt">
                <van-button @click="pushExamine()" type="primary">提交审核</van-button>
                <van-button @click="goAddStaff()" type="info">新增员工</van-button>
                <van-button @click="delUser()" type="warning">删除员工</van-button>
            </div>
        </div>
    </div>
</template>

<script>
    // confirmDialog
    export default {
        name: "kfStaffList",
        components: {},
        data() {
            return {
                order_id: '',

                searchVal: '',

                timeField1: false,
                timeVal1: new Date(),
                timePopupShow1: false,

                minDate: new Date(2020, 0, 1),
                maxDate: new Date(2025, 10, 1),
                currentDate: new Date(),

                tableData: [],
                page: 1,
                limit: 10,
                pageCount: 1,

                tableSelectValArr: [],

                button1: false,
                button2: false,
                timeValue: '',
            }
        },
        methods: {
            // 是否可选中
            checkSelectable(row) {
                return row.is_verify != 1
            },
            formatter(type, value) {
                if (type === 'year') {
                    return `${value}年`;
                } else if (type === 'month') {
                    return `${value}月`
                }
                return value;
            },
            feedback(data) {
                this.$router.push(`/kfFeedback?id=${data.id}`)

            },
            timeConfirm1() {
                this.timeField1 = true;
                this.timePopupShow1 = false;
                this.timeValue = this.$formatDateTime(this.timeVal1, 'yyyy-MM')
                let Month = this.timeVal1.getMonth() + 1
                this.timeValue = this.$formatDateTime(this.timeVal1, 'yyyy-MM')
                this.inspect();
            },
            setUserInfo(val) {
                localStorage.setItem('tbTime', this.timeValue)
                this.$router.push(`/kfAddStaff?userId=${val.id}&goodsId=${this.$route.query.goodsId}&oid=${this.order_id}&type=set`)
            },
            goAddStaff(index) {
                localStorage.setItem('tbTime', this.timeValue)
                this.$router.push(`/kfAddStaff?id=${this.$route.query.id}&goodsId=${this.$route.query.goodsId}&oid=${this.order_id}&type=add`)
            },

            tableSelectChange(val) {
                this.tableSelectValArr = val;
            },
            onSearch() {
                this.page = 1;
                this.getList();
            },
            pageChange() {
                this.getList();
            },
            getList() {
                let params = {
                    wx_member_id: localStorage.getItem('wx_member_id'),
                    token: localStorage.getItem('token'),
                    order_id: this.order_id,
                    member_goods_id: this.$route.query.id,
                    cate_id: 1,
                    page: this.page,
                    limit: this.limit,
                    month: this.$formatDateTime(this.timeVal1, 'yyyy-MM'),
                };

                this.$post("/api/order_detail/add", params)
                    .then(res => {
                        if (res.code == 1) {
                            this.pageCount = res.data.totalPage // 发票类型
                            this.tableData = res.data.dataList // 发票类型
                            this.$Toast.clear();
                        }
                    }).catch(err => {
                });
            },
            inspect() {

                let params = {
                    wx_member_id: localStorage.getItem('wx_member_id'),
                    token: localStorage.getItem('token'),
                    member_goods_id: this.$route.query.id,
                    month: this.timeValue

                };
                this.$post("/api/order_detail/pre_add", params)
                    .then(res => {
                        if (res.code == 1) {
                            // 当月未创建订单
                            if (res.data.type == 1) {
                                this.$Toast.clear();
                                this.$Dialog.confirm({
                                    title: '温馨提示',
                                    message: `当前月份未创建订单，确认创建订单么？`,
                                    closeOnPopstate: true,
                                })
                                    .then(() => {
                                        let params = {
                                            wx_member_id: localStorage.getItem('wx_member_id'),
                                            token: localStorage.getItem('token'),
                                            member_goods_id: this.$route.query.id,
                                            month: this.$formatDateTime(this.timeVal1, 'yyyy-MM'),
                                        };
                                        this.$post("/api/order_detail/create_order", params)
                                            .then(res => {
                                                if (res.code == 1) {
                                                    // 当月未创建订单
                                                    this.order_id = res.data
                                                    this.$Toast(res.msg);
                                                    this.inspect()
                                                } else {
                                                    this.$Toast(res.msg);
                                                }
                                            })
                                            .catch(err => {
                                            });
                                    })
                                    .catch(() => {
                                    });
                            }
                            // 可编辑订单
                            if (res.data.type == 2) {
                                this.order_id = res.data.order_id
                                this.getList();
                            }
                            // 只能读取订单
                            if (res.data.type == 3) {
                                this.$Toast.clear();
                                this.$Dialog.confirm({
                                    title: '温馨提示',
                                    message: `您当前月已投保完毕，如需继续投保请重新选择时间。`,
                                    closeOnPopstate: true,
                                    cancelButtonText: '查看本月投保订单',
                                    confirmButtonText: '投下月订单',
                                }).then(() => {
                                    let nextMonth = Number(this.timeValue.slice(-2)) + 1
                                    let newYear = Number(this.timeValue.slice(0, 4))
                                    let nextTime = this.timeValue.slice(-3)
                                    if (nextMonth < 10) {
                                        nextMonth = `-0${nextMonth}`
                                        this.timeValue = this.timeValue.replace(nextTime, nextMonth)
                                    }
                                    if (nextMonth == 13) {
                                        nextMonth = '01'
                                        this.timeValue = this.timeValue.replace(newYear, newYear + 1)
                                        this.timeValue = this.timeValue.replace(nextTime, nextMonth)
                                    }
                                    this.inspect()

                                }).catch(() => {
                                    this.$router.replace(`kfOrderUserList?id=${res.data.order_id}`)
                                });
                            }
                        }
                    })
                    .catch(err => {
                    });
            },
            // 删除人员
            delUser() {
                if (this.tableSelectValArr.length == 0) {
                    this.$Toast('请选择删除人员');
                    return;
                }
                let userArr = []
                this.tableSelectValArr.map((item, index) => {
                    userArr.push(item.id)
                })

                this.$Dialog.confirm({
                    title: '温馨提示',
                    message: `确认删除这 ${userArr.length} 个人么？`,
                    closeOnPopstate: true,
                })
                    .then(() => {
                        let params = {
                            wx_member_id: localStorage.getItem('wx_member_id'),
                            token: localStorage.getItem('token'),
                            id: userArr,
                        };
                        this.$post("/api/order_detail_roster/del", params)
                            .then(res => {
                                if (res.code == 1) {
                                    this.onSearch()
                                    this.$Toast(res.msg);
                                } else {
                                    this.$Toast(res.msg);
                                }
                            })
                            .catch(err => {
                            });

                    })
                    .catch(() => {
                    });

            },
            // 提交审核
            pushExamine() {
                if (this.tableSelectValArr.length == 0) {
                    this.$Toast('请选择审核人员');
                    return;
                }
                let userArr = []
                this.tableSelectValArr.map((item, index) => {
                    userArr.push(item.id)
                })

                this.$Dialog.confirm({
                    title: '温馨提示',
                    message: `确认审核这 ${userArr.length} 个人么？`,
                    closeOnPopstate: true,
                })
                    .then(() => {
                        let params = {
                            wx_member_id: localStorage.getItem('wx_member_id'),
                            token: localStorage.getItem('token'),
                            order_id: this.order_id,
                            ids: userArr,
                            orderstatus: 20, // 10 保存 20 提交审核
                        };
                        this.$post("/api/order_detail/apply_check", params)
                            .then(res => {
                                if (res.code == 1) {
                                    setTimeout(() => {
                                        // this.onSearch()
                                        this.$router.go(-1)
                                    }, 1500);
                                    this.$Toast(res.msg);
                                } else {
                                    this.$Toast(res.msg);
                                }
                            })
                            .catch(err => {
                            });

                    })
                    .catch(() => {
                    });
            }
        },
        created() {
            this.timeValue = this.$formatDateTime(this.timeVal1, 'yyyy-MM')
            let tbTime = localStorage.getItem("tbTime");
            if (tbTime) {
                this.timeValue = tbTime
            }

            this.button1 = this.$queryMenu('Customer/add_staff')
            this.button2 = this.$queryMenu('Customer/del_staff')

            this.$Toast.loading({
                duration: 0, // 持续展示 toast
                message: '加载中...',
                forbidClick: true
            });
            let time = new Date()
            this.minDate = new Date(time.getFullYear(), time.getMonth(), time.getDate())

            this.inspect();
            localStorage.removeItem("tbTime");

        },

    }
</script>

<style scoped lang="less">
    .kfStaffList {
        padding: 16px;
        padding-top: 0;
    }

    .pagination {
        margin-top: 11px;
    }

    .date-box {
        display: flex;
        flex-wrap: nowrap;
        align-items: center;
        padding: 11px;

        > div:nth-of-type(1) {
            width: 70px;
        }
    }

    .line {
        display: flex;
        align-items: center;

        .border-line {
            border: 1px solid #dcdcdc;
            padding: 0 2px;
            margin: 0 3px;
            border-radius: 3px;
        }

        .time-text {
            flex-wrap: nowrap;
            width: 50px;
            font-size: 15px;
            color: #333333;
        }

        > .money-box {
            position: relative;

            > div {
                flex: 1;
                margin: 3px 6px;
                border: 1px solid #dcdcdc;
                color: #333;
                border-radius: 5px;
            }

            > .money-box {
                position: relative;

                span {
                    position: absolute;
                    right: 10px;
                    top: 50%;
                    transform: translateY(-50%);
                }

                input {
                    border: none;
                    padding-left: 6px;
                    height: 25px;
                    width: 112px;
                    padding-right: 10px;
                    font-size: 11px;
                    text-align: right;
                }
            }
        }
    }

    .table-box {
        overflow-x: scroll;
    }

    .bottom-bt {
        margin-top: 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
</style>